import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-datepicker/dist/css/bootstrap-datepicker3.css';
require('../css/purchase/pubprice.less');
require('../css/purchase/index.less');
require('../css/purchase/common.less');



var $ = require('jquery');
import 'bootstrap/dist/js/bootstrap.min.js';
import 'bootstrap-datepicker/dist/js/bootstrap-datepicker.js';
import 'jquery-validation/dist/jquery.validate.js';
import 'jquery-validation/dist/localization/messages_zh.js';

let headerTemplate = require('../view/templateWidget/header.hbs');
let footerTemplate = require('../view/templateWidget/footer.hbs');
let sheetContTemplate = require('../view/templateWidget/sheetCont.hbs');
let conitGoodsTemplate = require('../view/templateWidget/conitGoods.hbs');

$('header').html(headerTemplate);
$('footer').html(footerTemplate);

require('../helper/header.js'); //搜索栏切换placeholder及搜索为空校验
require('../helper/helper.js'); // 日期插件切换为中文显示

// var parUrl = window.location.href.split("?")[1];
// var purchId = parUrl.split("=")[1];
// console.log(purchId);

// 选中报价不含税时隐藏税率输入框
$('input[name="is_taxed"]').click(function () {
    if ($(this).val() === "0") {
        $("#invoice_type").val("");
        $("#tax_rate").val("");
        $("#taxRate").hide();
    } else {
        $("#taxRate").show();
    }
});
// 客户类型是企业采购时显示公司名称
$('input[name="typeFlag"]').click(function () {
    if ($(this).val() === "0") {
        $(".company_name").hide();
    } else {
        $(".company_name").show();
    }
});

$.ajax({
    type: "get",
    url: "http://purchasing.mhw001.com/getPurchasingDetail?purchase_id=723",
    dataType: "json",
    // data:{
    //     purchase_id:purchId
    // },
    xhrFields: {
        withCredentials: true
    },
    success: function (result) {
        console.log(result.data);
        // 请求参数purchase_id、goods_id
        var purchaseId = result.data.purchase_id;
        $("#purchase_id").val(purchaseId);
        var goodsId = result.data.goods_id;
        $("#goods_id").val(goodsId);
        // 获取报价单内容
        $('#introCont').html(sheetContTemplate({
            data: result.data
        }));
        // 模板加载进来之后处理采购类型
        var res = result.data.purchase_type;
        if (res == "0") {
            $(".purGoodsType").text("现货/标准品");
        } else if (res == "1") {
            $(".purGoodsType").text("加工/定制品");
        }
        var conit = result.data.offer_demand;
        // console.log(conit);
        if (conit == null) {
            $(".conitt").hide();
        }else if (conit.length == 2) {
            $(".conittList").text("报价含税，报价含运费");
        }else if (conit.length == 1) {
            if (conit[0] == 0) {
                $(".conittList").text("报价含税");
            } else if (conit[0] == 1) {
                $(".conittList").text("报价含运费");
            }
        }
        // console.log(result.data.goods_info);
        $('#conit_goods').html(conitGoodsTemplate({
            data: result.data.goods_info
        }));
        resetIndex();
        initDataPick();
        // 判断是要发布还是修改
        $.ajax({
            type: "get",
            url: "http://purchasing.mhw001.com/getOfferInfoByShopId?purchase_id=723",
            data:{
                purchase_id:purchId
            },
            dataType: "json",
            success: function (result) {
                console.log(result);
                if(result!=""){
                    FormUtil.set(result);
                    // 是否含税
                    var isTax = result.is_taxed;
                    if(isTax=="1"){
                        $("#taxFlagYes").attr("checked","true");
                        $("#taxRate").show();
                    }else{
                        $("#taxFlagNo").attr("checked","true");
                    }
                    //是否含运费
                    var isFreight = result.is_freighted;
                    if(isFreight=="1"){
                        $("#carrFlagYes").attr("checked","true");
                    }else{
                        $("#carrFlagNo").attr("checked","true");
                    }
                    // 单价
                    var unitPrice = result.goods_info.unit_price;
                    $("input[name^='unit_price']").each(function (i) {
                        $(this).val(unitPrice[i]);
                    });
                    //有效期
                    var validDate = result.goods_info.valid_date;
                    $("input[name^='valid_date']").each(function (i) {
                        $(this).val(validDate[i]);
                    });
                    //备注
                    var goodsRemark = result.goods_info.goods_remark;
                    $("textarea[name^='goods_remark']").each(function (i) {
                        $(this).val(goodsRemark[i]);
                    });
                }
            }
        });

    }
});

//用于发布报价表单验证
// 验证手机号码
var vali;
$.validator.addMethod("isMobile", function (value, element) {
    var length = value.length;
    var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
    return this.optional(element) || (length == 11 && mobile.test(value));
});
vali = $("#signupForm").validate({
    // debug: true, //调试模式，即使验证成功也不会跳转到目标页面
    rules: {
        is_taxed: "required",
        invoice_type: "required",
        tax_rate: 'required',
        is_freighted: 'required',
        offer_company: 'required',
        offer_contact: 'required',
        offer_mobile: {
            required: true,
            isMobile: true
        },
        pubFlag: 'required'
    },
    messages: {
        is_taxed: "请选择报价是否含税",
        invoice_type: "请选择发票类别",
        tax_rate: '请输入税率',
        is_freighted: '请选择报价是否含税',
        offer_company: '请输入公司名称',
        offer_contact: '请输入联系人',
        offer_mobile: {
            required: "请输入手机号",
            isMobile: "请正确填写您的手机号码"
        },
        pubFlag: '请选择信息公开方式'
    },
    errorPlacement: function (error, element) {
        error.appendTo(element.parent());
    },
});

// 重置索引及动态添加表单校验
function resetIndex() {
    $('.conit_line').each(function (i) {
        //获取当前tr的id
        var id = $(this).attr('id');
        $(this).attr('id', id.replace(/\d/, i));
        $(this).find('.everyConit').each(function () {
            var obj = $(this);
            var id = $(obj).attr('id');
            var name = $(obj).attr('name');
            $(obj).attr('id', id.replace(/\d/, i));
            $(obj).attr('name', name.replace(/\d/, i));
            var newId = $(this).attr('id');
            $(obj).next().attr('for', newId);
        });
    });
    $("input[name^='unit_price']").each(function () {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "请输入单价"
            }
        });
    })
    $("input[name^='valid_date']").each(function () {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "请选择价格有效期"
            }
        });
    })
}

function initDataPick() {
    $("input[name^='valid_date']").each(function () {
        $(this).datepicker({
            autoclose: true, //自动关闭  
            format: 'yyyy-mm-dd', //日期格式 
            language: 'cn', //语言
            todayHighlight: true, //今天高亮
            startDate: new Date(),
        })
    })
    // 选择日期之后删除错误提示
    $("input[name^='valid_date']").each(function () {
        $(this).on('change', function () {
            $(this).focus();
            $(this).blur();
        })
    })
}
// 单价失去焦点时自动计算总计
$("#conit_goods").delegate('.unit_price', 'blur', function () {
    $('#total_price').val(function () {
        var totalFee = 0;
        $('#conit_goods').find('tr').each(function () {
            var amount = $($(this).find('.amount_purchased')[0]).text();
            var unit = $($(this).find('.unit_price')[0]).val();
            if (!amount) {
                amount = 0;
            }
            if (!unit) {
                unit = 0
            }
            totalFee += amount * unit;
        });
        return totalFee;
    });
});
// 提交表单
$('.imd_pub_btn').on('click', function () {
    if (vali.form()) {
        var formCont = new FormData($("#signupForm")[0]);
        $.ajax({
            type: "POST",
            url: 'http://purchasing.mhw001.com/addOfferList',
            data: formCont,
            cache: false,
            processData: false,
            contentType: false,
            // async: false,  
            success: function (data) {
                console.log(data);
                $.ajax({
                    type: "get",
                    url: "http://purchasing.mhw001.com/getPurchasingDetail",
                    data:{
                        purchase_id:purchId
                    },
                    dataType: "json",
                    success: function (result) {
                        // 发布成功调用信息详情接口报价+1
                    }
                });
                console.log(data);
                alert("发布成功!");
                // 返回上一页
                //window.location.go(-1);
                self.location = document.referrer; 
            },
            error: function (request) {
                alert("系统错误!");
            }
        });
    } else {
        return false;
    }
})

var FormUtil={  
    //值回写方法 
    set:function(obj){  
        var attr;  
        for(attr in obj){
            try{
                var element=$("#"+attr)[0];  
                var nodeName=element.nodeName;  
                if(nodeName=="INPUT"){  
                    FormUtil.judgeType($(element).attr("type"),attr,obj[attr]);  
                }else if(nodeName=="SELECT"){  
                    FormUtil.setSelect(attr,obj[attr]);  
                }else if(nodeName=="TEXTAREA"){  
                    FormUtil.setValue(attr,obj[attr]);  
                }
            }catch(e){
                continue;
            }
        }  
    },  
    //设置文本框 文本域 密码框 隐藏框  
    setValue:function(key,value){  
        $("#"+key).val(value);  
    },  
    //设置下拉框  
    setSelect:function(key,value){  
        $("#"+key+" option").each(function(){  
            if(this.value==value){  
                $(this).attr("selected","selected");  
            }  
        });  
    },     
    //input类型判断  
    judgeType:function(type,key,value){  
        if(type=="text"||type=="password"||type=="hidden"){  
            FormUtil.setValue(key,value);  
        }else if(type=="radio"){  
            FormUtil.setRadio(key,value);  
        }
    }  
}; 